package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Override//根据手机号查询会员信息
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override//添加会员
    public void add(Member member) {
        //添加之前先查看用户是否有登录密码，如果有对密码进行加密
        String password = member.getPassword();
        if (password != null) member.setPassword(MD5Utils.md5(password));
        memberDao.add(member);
    }

    @Override//根据年月日期查询会员数量用于报表统计
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }

    @Override
    public List<Map<String, Object>> findGenderByMember() {
        return memberDao.findGenderByMember();
    }

    @Override
    public List<Map<String, Object>> findAgeByMember() {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> ageByMember = memberDao.findAgeByMember();
        Set<String> keySet = ageByMember.keySet();//获取所有年龄段的值,即key值
        for (String key : keySet) {
            Map<String, Object> map = new HashMap<>();
            BigDecimal value = (BigDecimal) ageByMember.get(key);//获取年龄段对应的数值
            map.put("value", value);//将当前年龄段的值封装到value中
            map.put("name", key);//将当前的年龄段封装到name中
            list.add(map);//添加到list集合中
        }
        return list;
    }
}
